<script setup lang="ts">
import {getCurrentInstance, reactive, ref} from "vue";
import {type UserInfoUpdateReq, userUpdateAxios} from "@/api/user_api";
import {Message, type TableData} from "@arco-design/web-vue";
import {roleOptions} from "@/global/global";

const updateData = reactive<UserInfoUpdateReq>({
  id: null,
  role: 1,
  nick_name: "",
})

const visible = ref(false);

const mitt = getCurrentInstance()

mitt?.proxy?.$Bus.on('openUpdateModal', (record) => {
  visible.value = true
  let record1 = record as TableData;
  updateData.id = record1.id
  updateData.nick_name = record1.nick_name
  switch (record1.role) {
    case "管理员":
      updateData.role = 1
      break
    case "普通登录人":
      updateData.role = 2
      break
    case "游客":
      updateData.role = 3
      break
    case "被禁用的用户":
      updateData.role = 4
      break
  }
})

const formRef = ref()

async function updateUser() {
  // val是undefined则表示校验通过
  let val = await formRef.value.validate()
  if (val) {
    return false
  }
  let rsp = await userUpdateAxios(updateData);
  if (rsp.code !== 0) {
    Message.error("修改失败")
    return false
  }
  Message.success("修改成功")
  mitt?.proxy?.$Bus.emit("refresh")
  close()
}

function close() {
  visible.value = false
}

</script>

<template>
  <a-modal title="编辑用户" :visible="visible" :on-before-ok="updateUser" @cancel="close">
    <a-form ref="formRef" :model="updateData">

      <a-form-item field="nick_name" label="昵称" :rules="[{required:true,message:'请输入昵称'}]"
                   validate-trigger="blur">
        <a-input v-model="updateData.nick_name" placeholder="昵称"></a-input>
      </a-form-item>

      <a-form-item field="re_password" label="选择权限">
        <a-select v-model="updateData.role" :options="roleOptions" placeholder="选择权限"></a-select>
      </a-form-item>

    </a-form>
  </a-modal>
</template>

<style scoped>

</style>
